package com.czl.module_base.utils;

import android.text.TextUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author by xubin,
 * @date on 2022/2/14.
 * PS: Not easy to write code, please indicate.
 */
public class NumberUtils {
    private static final Pattern PATTERN_NUMBER = Pattern.compile("^[0-9]*$");
    private static final Pattern PATTERN_DOUBLE = Pattern.compile("^[-+]?\\d+(\\.\\d*)?|\\.\\d+$");

    public static double decimalPoints(double d, int digits) {
        BigDecimal bg = new BigDecimal(d);
        return bg.setScale(digits, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public static String decimalPoints2(double d, int digits) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(digits);
        return nf.format(d);
    }

    public static String decimalPoints2(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(d);
    }

    public static String decimalPoints(String s) {
        if (isDouble(s)) {
            DecimalFormat format = new DecimalFormat("0.00");
            return format.format(new BigDecimal(s));
        }
        return "0.00";
    }

    public static boolean greaterThanZero(double d) {
        return Double.doubleToLongBits(d) > Double.doubleToLongBits(0);
    }

    public static String doubleTrans(double d) {
        if (Math.round(d) - d == 0) {
            return String.valueOf((long) d);
        }
        return String.valueOf(d);
    }

    public static boolean isNumber(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        Matcher matcher = PATTERN_NUMBER.matcher(str);
        return matcher.matches();
    }

    public static int parseInt(String str) {
        if (isNumber(str)) {
            return Integer.parseInt(str);
        }
        return 0;
    }

    public static boolean isDouble(String str) {
        return PATTERN_DOUBLE.matcher(str).matches();
    }
}
